/**
 * 
 */
package vo;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

/**
 * @author Saulo
 *
 */
public class MaterialDAO {
	
	//SALVAR MATERIAL
		public void salvarMaterial(MaterialVO material) {

			Transaction transaction = null;

			Session session = HibernateUtil.currentSession();
			transaction = session.beginTransaction();

			session.saveOrUpdate(material);

			transaction.commit();

		}
		
		//EXCLUIR MATERIAL
		public void excluir(Integer idMat) {
		Transaction transaction = null;

		MaterialVO material = obter(idMat);
		
		Session session = HibernateUtil.currentSession();
		transaction = session.beginTransaction();

		session.delete(material);

		transaction.commit();
	}
		
		//OBTER MATERIAL
		public MaterialVO obter(Integer idMat) {
			Transaction transaction = null;

			Session session = HibernateUtil.currentSession();
			transaction = session.beginTransaction();

			Criteria criteria = session.createCriteria(MaterialVO.class);
			criteria.add(Restrictions.eq("idMat", idMat));

			MaterialVO material = (MaterialVO) criteria.uniqueResult();

			transaction.commit();

			return material;
		}

		@SuppressWarnings("unchecked")
		public List<MaterialVO> consultarMateriais(MaterialVO materialConsulta) {
			List<MaterialVO> listaDeMateriais = new ArrayList<MaterialVO>();

			Transaction transaction = null;

			Session session = HibernateUtil.currentSession();
			transaction = session.beginTransaction();

			Criteria criteria = session.createCriteria(MaterialVO.class);
			
			criteria.add(Restrictions.like("descriMat", materialConsulta.getDescriMat()+ "%"));

			listaDeMateriais = criteria.list();

			transaction.commit();
			return listaDeMateriais;
		}

		@SuppressWarnings("unchecked")
		public List<MaterialVO> consultarTodosMateriais() {
			List<MaterialVO> listaDeMateriais = new ArrayList<MaterialVO>();

			Transaction transaction = null;

			Session session = HibernateUtil.currentSession();
			transaction = session.beginTransaction();

			Criteria criteria = session.createCriteria(MaterialVO.class);

			listaDeMateriais = criteria.list();

			transaction.commit();
			return listaDeMateriais;
		}

		public MaterialVO consultarMaterialPorID(int id, Session session) {
			MaterialVO material = new MaterialVO();
			Criteria criteria = session.createCriteria(MaterialVO.class).add(Restrictions.eq("idMat", id));
			material = (MaterialVO) criteria.uniqueResult();
			return material;
		}
}
